package edu.zut.lxc.loveime.util;


import android.content.Context;
import android.content.SharedPreferences;

import android.os.Handler;
import android.os.Message;
import android.text.SpannableStringBuilder;
import android.util.Log;
import android.widget.Toast;


import androidx.annotation.NonNull;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;


import edu.zut.lxc.loveime.MyApp;
import edu.zut.lxc.loveime.constants.Constants;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * @author Astar
 * ClassName:OpenAIAPI.java
 * date:2023-03-03 16:49
 * Description:
 */
public  class OpenAIAPI {


    MyApp myApp = null;
    SharedPreferences sharedPreferences = null;


    /**
     * 发送消息
     *
     * @param txt 内容
     * @return {@link String}
     */

    public void chat(String txt, String pre_prompt, Handler mHandler) {
        myApp = MyApp.getInstance();
        sharedPreferences = myApp.getSharedPreferences("user_info",Context.MODE_PRIVATE);
        String base_url = sharedPreferences.getString("base_url","http://39.101.179.14:3000");
        String modal = sharedPreferences.getString("modal","deepseek-chat");

        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.remove(Constants.clipboardContent);
        String api_key = sharedPreferences.getString("api_key","未设置");
        if (api_key.equals("未设置")){
            Toast.makeText(myApp.getApplicationContext(), "未设置API_KEY",Toast.LENGTH_SHORT)
.show();
            Log.e("chat","未设置API_KEY");
            return;
        }
        Log.e("chat--","API_KEY:"+api_key + modal);



        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, "{\n    \n    \"model\": \""+modal+"\",\n    \"messages\": [\n      {\n        \"role\": \"system\",\n        \"content\": \""+pre_prompt+"\"\n      },\n      {\n        \"role\": \"user\",\n        \"content\": \""+txt+"\"\n      }\n    ]\n  }");
        Request request = new Request.Builder()
                .url(base_url+"/v1/chat/completions")
                .method("POST", body)
                .addHeader("Accept", "application/json")
                .addHeader("Authorization", "Bearer "+api_key)
                .addHeader("User-Agent", "Apifox/1.0.0 (https://apifox.com)")
                .addHeader("Content-Type", "application/json")
                .addHeader("Host", base_url.replace("http://",""))
                .addHeader("Connection", "keep-alive")
                .build();
                    client.newCall(request).enqueue(new Callback() {
                        @Override
                        public void onFailure(@NonNull Call call, @NonNull IOException e) {
                            Log.e("OPENAIAPI",e.fillInStackTrace().toString());
                            Log.e("OPENAIAPI",e.toString());

                        }
                        @Override
                        public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                            if (response.isSuccessful()){
                                String responseData = response.body().string();
                                Log.e("OPENAIAPI", responseData);
                                JSONObject json = null;
                                try {
                                    json = new JSONObject(responseData);
                                JSONArray choices = json.getJSONArray("choices");
                                JSONObject choice = choices.getJSONObject(0);
                                JSONObject message = choice.getJSONObject("message");
                                String content =  message.getString("content");
                                    Message msg = new Message();
                                        msg.what=-2;
                                        msg.obj=content;
                                    mHandler.sendMessage(msg);
                                    Log.e("OPENAIAPI", content);
                                } catch (JSONException e) {
                                    throw new RuntimeException(e);
                                }

                            }else {
                                Log.e("OPENAIAPI", "error");
                            }

                        }
                    });


            }

    }


